<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Request;
use Closure;
use DB;
class AdminAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $path = 'admin';
		$arr = explode('/',Request::path());
        $model = $arr[1];
        $action = $arr[2];
        $role_id = 1;
        if( ! empty($request->input('role_id')))
        {
            $role_id = intval($request->input('role_id'));
        }
        $access_arr = array();
        if($role_id == 1)
        {
            $access_arr = DB::table('node')->get();//超级管理员获取所有权限节点
        }
        else
        {
            //根据不同组来获取节点
            $access_arr = DB::table('role')->where('role.id','=',$role_id)->where('role.status','=',1)->leftJoin('access','access.role_id','=','role.id')->leftJoin('node',function($join)
            {
                $join->on('node.id','=','access.node_id')->on('node.pid','=','access.pid');
            })->select(array('node.*'))->get();
        }
        if(empty($access_arr))
        {
            return redirect('admin/msg/index');
        }
        $access_arr = $this->object_to_array($access_arr);
        $number = 0;
        foreach($access_arr as $key=>$val)
        {
            //后台入口权限
            if ($val['model'] === $path && $val['action'] === $path && intval($val['level']) === 1 ) 
            {
                $number ++;
            }
            //model权限
            if ($val['model'] === $model && $val['action'] === $model && intval($val['level']) === 2)   
                $number ++;
            //action权限
            if ($val['model'] === $model && $val['action'] === $action && intval($val['level']) === 3)  
                $number ++;
        }
        if($number !== 3)
        {
            return redirect('admin/msg/index');
        }
        return $next($request);
    }

	//将对象转成数组
	public function object_to_array($obj)
	{
		$_arr = is_object($obj) ? get_object_vars($obj) :$obj;
		foreach ($_arr as $key=>$val)
		{
			$val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
			$arr[$key] = $val;
		}
		return $arr;
	}    
}
